package com.jlastu.znb.adapter;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.jlastu.znb.R;
import com.jlastu.znb.gwc.CartItem;

import java.util.List;
import java.util.Locale;

public class CartAdapter extends ArrayAdapter<CartItem> {
    private Context context;
    private List<CartItem> cartItems;

    public CartAdapter(Context context, List<CartItem> cartItems) {
        super(context, R.layout.item_cart, cartItems);
        this.context = context;
        this.cartItems = cartItems;
//        super(context, 0, cartItems);
//        this.context = context;
//        this.cartItems = cartItems;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 复用convertView以优化性能
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_cart, parent, false);
        }

        CartItem cartItem = cartItems.get(position);
        ImageView itemImageView = convertView.findViewById(R.id.imageViewProduct);
        TextView itemNameView = convertView.findViewById(R.id.cart_item_name);
        TextView itemPriceView = convertView.findViewById(R.id.cart_item_price);
        TextView itemQuantityView = convertView.findViewById(R.id.cart_item_quantity);
        Bitmap bitmap = cartItem.getBitmap();
        if (!cartItem.hasImage()) {
            convertView.setVisibility(View.GONE);
            itemImageView.setVisibility(GONE);
        } else {
            convertView.setVisibility(View.VISIBLE);
            itemImageView.setImageBitmap(cartItem.getBitmap());
        }
        if (itemImageView != null && bitmap != null) {
            itemImageView.setImageBitmap(bitmap);
        } else if (itemImageView != null ){
            itemImageView.setImageResource(R.drawable.xiandou);
        }
        itemNameView.setText(cartItem.getGoodsName());
        double price = cartItem.getGoodsPrice(); // 获取单价
        int quantity = cartItem.getQuantity(); // 获取数量
        double totalPrice = price * quantity; // 计算总价

        itemPriceView.setText(String.format(Locale.getDefault(), "¥ %.2f", totalPrice));

        itemQuantityView.setText(String.valueOf(cartItem.getQuantity()));
        return convertView;
    }
}